package com.pai4j.log.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import jakarta.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 日志异步配置类
 *
 * @author: CYM-pai
 * @date: 2025/07/29 16:15
 **/
@Slf4j
@Configuration
@EnableAsync
public class LogAsyncConfig {

    @Resource
    private LogProperties logProperties;

    /**
     * 日志异步执行器
     *
     * @return 线程池执行器
     */
    @Bean("logAsyncExecutor")
    public Executor logAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        LogProperties.AsyncConfig asyncConfig = logProperties.getAsync();

        // 核心线程数
        executor.setCorePoolSize(asyncConfig.getCorePoolSize());

        // 最大线程数
        executor.setMaxPoolSize(asyncConfig.getMaxPoolSize());

        // 队列容量
        executor.setQueueCapacity(asyncConfig.getQueueCapacity());

        // 线程名前缀
        executor.setThreadNamePrefix(asyncConfig.getThreadNamePrefix());

        // 拒绝策略：调用者运行策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 等待时间
        executor.setAwaitTerminationSeconds(asyncConfig.getAwaitTerminationSeconds());

        // 初始化
        executor.initialize();

        log.info("日志异步线程池初始化完成，核心线程数：{}，最大线程数：{}，队列容量：{}",
                asyncConfig.getCorePoolSize(),
                asyncConfig.getMaxPoolSize(),
                asyncConfig.getQueueCapacity());

        return executor;
    }
}
